<template>
  <el-form :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="用户账号">
      <el-input v-model="form.name" />
    </el-form-item>
    <el-form-item label="用户密码">
      <el-input v-model="form.password" />
    </el-form-item>
    <el-form-item label="用户手机">
      <el-input v-model="form.tel" />
    </el-form-item>
    <el-form-item label="用户邮箱">
      <el-input v-model="form.email" />
    </el-form-item>
    <el-form-item label="用户性别">
      男<el-switch v-model="form.sex" style="margin-left: 5px;margin-right: 5px"/>女
    </el-form-item>
    <el-form-item label="用户生日">
      <el-col :span="11">
        <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="请选择一个日期"
            style="width: 100%"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
        />
      </el-col>
    </el-form-item>
    <el-form-item label="用户等级">
      <el-input-number v-model="form.level" :step="1" :min="0" :max="100"/>
    </el-form-item>
    <el-form-item label="用户余额">
      <el-input-number v-model="form.money" :min="0" :max="1000" />
    </el-form-item>
    <el-form-item label="个人签名">
      <el-input v-model="form.sign_text" type="textarea" />
    </el-form-item>
    <el-form-item label="状态">
      <el-select v-model="form.status" placeholder="请选择用户状态">
        <el-option label="启用" value="online" />
        <el-option label="禁用" value="offline" />
        <el-option label="隐藏" value="hide" />
      </el-select>
    </el-form-item>
<!--    <el-form-item>
      <view class="btn-items">
        <el-upload
            :action="fanart_uploadUrl"
            :http-request="fanart_uploadFile"
            accept="image/jpg"
            :show-file-list="false"
            :before-upload="beforeUpload"
        >
          <el-button size="small" type="primary">上传用户头像</el-button>
        </el-upload>
      </view>
    </el-form-item>-->
    <el-form-item>
      <el-button type="primary" @click="onSubmit">添加用户</el-button>
      <el-button @click="emit('close-dialog')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {reactive, onMounted} from 'vue'
import {ElLoading, ElMessage} from 'element-plus'
import {md5} from "js-md5";
import { defineProps } from 'vue';
import { defineEmits } from 'vue';
import router from "@/router";

const emit = defineEmits(['close-dialog'])

// const props = defineProps({
//   MID: String,
//   cancel: Boolean,
// });

const openFullScreen = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  return loading;
};

// 表单的响应式数据
const form = reactive({
  name: '',
  status: '',
  date: '',
  level: '',
  sign_text: '',
  money: 0,
  password:'',
  email:'',
  tel:'',
  sex: false,
})

// 上传相关的数据和方法
const account_addUrl = 'https://movie.cpb2013.top/admin/account.php?mode=add' // 替换为你的上传地址

const closeFullScreen = (loading) => {
  loading.close();
};
// 表单提交处理函数
const onSubmit = async () => {
  console.log('提交表单:', form)
  let loading = openFullScreen();
  const formData = new FormData()
  // const { name, status, date, level, desc, like, comment, love, stars, score, type, MID, length } = toRefs(form);
  formData.append('key', localStorage.getItem('key'));
  // 遍历并添加到 FormData
  Object.keys(form).forEach((key) => {
    // 排除那些不是字符串或数字的键（例如布尔值或对象）
    // 因为 FormData 主要用于处理键值对形式的字符串数据
    if (typeof form[key] === 'string' || typeof form[key] === 'number') {
      formData.append(key, form[key]);
    } else if (typeof form[key] === 'boolean') {
      // 对于布尔值，你可以决定如何转换为字符串（例如，使用 'true' 或 'false'）
      formData.append(key, form[key] ? '女' : '男');
    }
  });

  formData.append('date', form.date); // 直接添加 form.type 的值
  formData.set('password',md5(form.password));

  try {
    const response = await fetch(account_addUrl, {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    })

    if (response.ok) {
      const result = await response.json()
      if(result['status'] ==='success')
      {
        ElMessage.success('添加成功！')
        clearForm();
        // emit('close-dialog')
        // this.$emit('close-dialog');
      }else if (result['status'] === 'danger') {
        localStorage.removeItem('key');
        ElMessage.error(result['msg']);
        await router.push('/login'); // Use router to navigate to the login page
      }
      else
      {
        ElMessage.error(result['msg'])
      }
    } else {
      ElMessage.error('添加失败！')
    }
  } catch (error) {
    ElMessage.error('添加失败！')
  }
  closeFullScreen(loading)
}

onMounted(() => {
  // const MID = '06a718d656fac9f771507e1872adc838'; // replace with actual MID
  /*fetchMovieData(props.MID);/!**!/*/
});

function clearForm() {
  for (const key in form) {
    if (form.hasOwnProperty(key)) {
      // Set each property to its initial value
      switch (typeof form[key]) {
        case 'string':
          form[key] = '';
          break;
        case 'number':
          form[key] = 0;
          break;
        case 'boolean':
          form[key] = false;
          break;
        default:
          form[key] = '';
      }
    }
  }
}

/*watch(() => props.MID, (newMID) => {
  fetchMovieData(newMID);
});*/

</script>
